package com.lyn.solitude.pluginhost.uitls

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import java.io.ByteArrayOutputStream


/**
 *
 * @author longyn 2024/05/15
 * @version 1.0.0
 */
object BitmapUtil {

    @JvmStatic
    fun drawableToBitmap(drawable: Drawable): Bitmap {
        // 取 drawable 的长宽
        val w = drawable.intrinsicWidth
        val h = drawable.intrinsicHeight

        // 取 drawable 的颜色格式
        val config =
            if (drawable.alpha != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        // 建立对应 bitmap
        val bitmap = Bitmap.createBitmap(w, h, config)
        // 建立对应 bitmap 的画布
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, w, h)
        // 把 drawable 内容画到画布中
        drawable.draw(canvas)
        return bitmap
    }


    @JvmStatic
    fun bitmapToByteArray(bitmap: Bitmap): ByteArray? {
        try {
            val outputStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            val bytes = outputStream.toByteArray()
            outputStream.flush()
            outputStream.close()
            bitmap.recycle()
            return bytes
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return null
    }
}